package image2;

import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;

import java.util.ArrayList;
import java.util.List;

public class Interpolation {
    public static ArrayList<Double> interpolate(ArrayList<Double> x, ArrayList<Double> y, int targetLength) {
        ArrayList<Double> newY = new ArrayList<Double>(targetLength);

        // 计算步长
        double step = (double) (x.size() - 1) / (targetLength - 1);
        double currentStep = 0;

        // 循环所有的目标点
        for (int i = 0; i < targetLength; i++) {
            // 计算两个端点
            int leftIndex = (int) Math.floor(currentStep);
            int rightIndex = (int) Math.ceil(currentStep);
            if (rightIndex >= y.size() -1) {
                rightIndex = y.size()-1;
            }

            // 计算插值
            double fraction = currentStep - leftIndex;
            double leftValue = y.get(leftIndex);
            double rightValue = y.get(rightIndex);
            double newValue = leftValue + fraction * (rightValue - leftValue);

            // 加入结果
            newY.add(newValue);

            // 更新当前步长
            currentStep += step;
        }

        return newY;
    }


    public static void main(String[] args) {
        ArrayList<Double> x = new ArrayList<Double>();
        x.add(483d);
        x.add(207d);
        x.add(426d);
        x.add(500d);

        ArrayList<Double> y = new ArrayList<Double>();
        y.add(190d);
        y.add(199d);
        y.add(144d);
        y.add(249d);

        int targetLength = 30;

        ArrayList<Double> newY = interpolate(x, y, targetLength);
        ArrayList<Double> newX = interpolate(y, x, targetLength);
        System.out.println(newX);
        System.out.println(newY);


        for (int i = 0; i < x.size(); i++) {
            x.set(i, x.get(i) - 1);
        }
        for (int i = 0; i < y.size(); i++) {
            y.set(i, y.get(i) - 1);
        }

        ArrayList<Double> newY2 = interpolate(x, y, targetLength);
        ArrayList<Double> newX2 = interpolate(y, x, targetLength);
        System.out.println(newX2);
        System.out.println(newY2);

        System.out.println(x);
        System.out.println(y);

        double v1 = euclideanDistance(newX, newX2);
        double v2 = euclideanDistance(newY, newY2);

        System.out.println((v1 + v2) / 2);
    }

    private static double euclideanDistance(List<Double> line1, List<Double> line2) {
        double sum = 0.0;
        for (int i = 0; i < line1.size(); i++) {
            sum += Math.pow(line1.get(i) - line2.get(i), 2);
        }
        return Math.sqrt(sum);
    }
}
